#!/usr/bin/env python3
"""直接运行 QuantAnalyzer 的 main 函数.

该脚本复制了 quant_analyzer.py 中 main 函数的逻辑，使用绝对导入避免循环导入问题。
"""

import sys
import logging
import json
from pathlib import Path

# 将项目根目录添加到 Python 路径
_project_root = Path(__file__).parent
if str(_project_root) not in sys.path:
    sys.path.insert(0, str(_project_root))

# 配置日志输出
logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
    datefmt="%Y-%m-%d %H:%M:%S",
)

logger = logging.getLogger(__name__)

def main(symbol: str | None = None) -> None:
    """执行 QuantAnalyzer 测试，使用真实 ETF 数据."""
    from src.data.fetcher import fetch_etf_history
    from src.features.pipeline import build_feature_dataframe
    from src.utils.state import GLOBAL_DATA_STORE
    from src.quant.quant_analyzer import QuantAnalyzer

    # 1. 确定要分析的 ETF 代码
    if symbol is None:
        if len(sys.argv) > 1:
            symbol = sys.argv[1]
        else:
            symbol = "515790"
    
    logger.info(f"开始获取真实 ETF 数据: symbol={symbol}")
    
    # 2. 从 AkShare 获取真实的 ETF 历史数据
    try:
        dataset = fetch_etf_history(symbol)
        logger.info(
            f"成功获取 ETF 数据: {dataset.symbol}, "
            f"数据量: {dataset.count} 条, "
            f"时间范围: {dataset.start.date()} 至 {dataset.end.date()}"
        )
    except Exception as e:
        logger.error(f"获取 ETF 数据失败: symbol={symbol}, error={e}")
        print(f"\n❌ 获取 ETF 数据失败: {e}")
        print(f"请检查 ETF 代码是否正确，或网络连接是否正常。")
        raise

    # 3. 检查数据量
    if dataset.count < 200:
        logger.warning(
            f"数据量不足: {dataset.symbol} 只有 {dataset.count} 条数据，"
            f"建议至少 200 条数据。可能会影响分析结果。"
        )
        print(f"\n⚠️  警告: 数据量不足（{dataset.count} 条），建议至少 200 条数据。")

    # 4. 存储数据集
    test_symbol = dataset.symbol
    GLOBAL_DATA_STORE.set_dataset(test_symbol, dataset)
    logger.info(f"已缓存 ETF 数据集: {test_symbol}, 数据量: {dataset.count} 条")

    # 5. 生成特征数据
    logger.info("开始生成特征数据...")
    try:
        features = build_feature_dataframe(dataset.frame)
        logger.info(f"特征生成完成: 原始数据 {len(dataset.frame)} 条，特征数据 {len(features)} 条")
    except Exception as e:
        logger.error(f"特征生成失败: {e}")
        print(f"\n❌ 特征生成失败: {e}")
        raise
    
    # 6. 创建目标变量
    if "收盘" in dataset.frame.columns:
        close_col = "收盘"
    elif "close" in dataset.frame.columns:
        close_col = "close"
    else:
        raise ValueError("无法找到收盘价列（收盘 或 close）")
    
    close = dataset.frame[close_col].loc[features.index]
    features["target_up"] = (close.shift(-1) > close).astype(int)
    
    # 7. 存储特征数据
    GLOBAL_DATA_STORE.set_features(test_symbol, features)
    logger.info(f"已生成并缓存特征数据: {test_symbol}, 特征数量: {len(features.columns)} 个")

    # 8. 创建量化分析器
    analyzer = QuantAnalyzer()

    # 9. 执行量化分析
    logger.info("开始执行量化分析（包含所有模型）...")
    print(f"\n{'=' * 80}")
    print(f"开始量化分析: {test_symbol}")
    if dataset.metadata and dataset.metadata.name:
        print(f"ETF 名称: {dataset.metadata.name}")
    print(f"数据时间范围: {dataset.start.date()} 至 {dataset.end.date()}")
    print(f"数据量: {dataset.count} 条")
    print(f"{'=' * 80}\n")
    
    try:
        result_json = analyzer.analyze(
            symbol=test_symbol,
            include_lstm=True,
            include_gru=True,
            include_temporal_cnn=True,
            include_catboost=True,
            include_mlp=True,
            enable_optimization=True,
        )

        # 10. 解析并打印结果
        result_dict = json.loads(result_json)
        
        print("\n" + "=" * 80)
        print("量化分析测试结果")
        print("=" * 80)
        print(f"\n标的代码: {result_dict['symbol']}")
        print(f"\n数据信息:")
        data_info = result_dict.get("data_info", {})
        print(f"  - 起始日期: {data_info.get('start_date', 'N/A')}")
        print(f"  - 结束日期: {data_info.get('end_date', 'N/A')}")
        print(f"  - 训练集样本数: {data_info.get('train_samples', 'N/A')}")
        print(f"  - 验证集样本数: {data_info.get('val_samples', 'N/A')}")
        print(f"  - 测试集样本数: {data_info.get('test_samples', 'N/A')}")
        
        print(f"\n最佳模型: {result_dict.get('best_model', 'N/A')}")
        
        # 打印模型指标
        print(f"\n模型评估指标:")
        model_metrics = result_dict.get("model_metrics", {})
        for model_name, metrics in model_metrics.items():
            print(f"  - {model_name}:")
            print(f"    AUC: {metrics.get('auc', 0.0):.4f}")
            print(f"    准确率: {metrics.get('accuracy', 0.0):.4f}")
            print(f"    F1分数: {metrics.get('f1', 0.0):.4f}")
            if metrics.get('is_overfitting', False):
                print(f"    ⚠️  存在过拟合风险")
        
        # 打印回测指标
        print(f"\n回测指标:")
        backtest_metrics = result_dict.get("backtest_metrics", {})
        best_model_name = result_dict.get("best_model", "")
        if best_model_name and best_model_name in backtest_metrics:
            best_metrics = backtest_metrics[best_model_name]
            print(f"  - 最佳模型 ({best_model_name}):")
            print(f"    累计收益率: {best_metrics.get('cumulative_return', 0.0):.4f}")
            print(f"    年化收益率: {best_metrics.get('annualized_return', 0.0):.4f}")
            print(f"    夏普比率: {best_metrics.get('sharpe_ratio', 0.0):.4f}")
            print(f"    最大回撤: {best_metrics.get('max_drawdown', 0.0):.4f}")
            print(f"    胜率: {best_metrics.get('win_rate', 0.0):.4f}")
        
        # 打印推荐信息
        recommendation = result_dict.get("recommendation", {})
        if recommendation:
            print(f"\n模型推荐:")
            print(f"  状态: {recommendation.get('status', 'N/A')}")
            primary = recommendation.get("primary", {})
            if primary:
                print(f"  主推荐模型: {primary.get('model', 'N/A')}")
                print(f"  推荐得分: {primary.get('score', 0.0):.4f}")
            
            notes = recommendation.get("notes", [])
            if notes:
                print(f"  备注:")
                for note in notes:
                    print(f"    - {note}")
        
        # 打印完整报告
        print("\n" + "=" * 80)
        print("完整分析报告（格式化文本）")
        print("=" * 80)
        formatted_text = analyzer.format_result(result_json)
        print(formatted_text)
        
        print("\n" + "=" * 80)
        print("测试完成！")
        print("=" * 80)

    except Exception as e:
        logger.error(f"量化分析执行失败: {e}", exc_info=True)
        print(f"\n❌ 测试失败: {e}")
        raise


if __name__ == "__main__":
    main()

